import { ConversationContext, ChatMessage, GameContext } from './types';
import { Entity } from '@/entities/Entity';

// 对话上下文管理器
export class ConversationContextManager {
  private contexts: Map<string, ConversationContext> = new Map();
  private maxHistoryLength = 50; // 每个对话保留的最大历史消息数
  private contextTimeout = 30 * 60 * 1000; // 30分钟后清理不活跃的上下文
  private lastCleanup = Date.now();
  private cleanupInterval = 5 * 60 * 1000; // 5分钟清理一次

  /**
   * 获取或创建实体的对话上下文
   */
  getOrCreateContext(entity: Entity, gameContext: GameContext): ConversationContext {
    const entityId = entity.getId();
    const entityType = entity.getType();
    const contextKey = `${entityType}_${entityId}`;

    let context = this.contexts.get(contextKey);
    
    if (!context) {
      // 创建新的对话上下文
      context = {
        entityId,
        entityType,
        history: [],
        gameContext
      };
      this.contexts.set(contextKey, context);
      console.log(`📝 为 ${entityType}(${entityId}) 创建新的对话上下文`);
    } else {
      // 更新游戏上下文
      context.gameContext = gameContext;
    }

    // 执行定期清理
    this.performPeriodicCleanup();

    return context;
  }

  /**
   * 更新对话上下文的历史记录
   */
  updateContextHistory(entityId: string, entityType: string, message: ChatMessage): void {
    const contextKey = `${entityType}_${entityId}`;
    const context = this.contexts.get(contextKey);
    
    if (context) {
      // 添加消息到历史记录
      context.history.push(message);
      
      // 限制历史记录长度
      if (context.history.length > this.maxHistoryLength) {
        context.history = context.history.slice(-this.maxHistoryLength);
      }
      
      console.log(`📝 更新 ${entityType}(${entityId}) 的对话历史，当前消息数: ${context.history.length}`);
    }
  }

  /**
   * 获取实体的对话历史
   */
  getContextHistory(entityId: string, entityType: string): ChatMessage[] {
    const contextKey = `${entityType}_${entityId}`;
    const context = this.contexts.get(contextKey);
    return context ? [...context.history] : [];
  }

  /**
   * 更新游戏上下文
   */
  updateGameContext(entityId: string, entityType: string, gameContext: GameContext): void {
    const contextKey = `${entityType}_${entityId}`;
    const context = this.contexts.get(contextKey);
    
    if (context) {
      context.gameContext = gameContext;
    }
  }

  /**
   * 清除特定实体的对话上下文
   */
  clearEntityContext(entityId: string, entityType: string): void {
    const contextKey = `${entityType}_${entityId}`;
    const removed = this.contexts.delete(contextKey);
    
    if (removed) {
      console.log(`🗑️ 清除 ${entityType}(${entityId}) 的对话上下文`);
    }
  }

  /**
   * 获取所有活跃的对话上下文
   */
  getActiveContexts(): { key: string; context: ConversationContext }[] {
    return Array.from(this.contexts.entries()).map(([key, context]) => ({
      key,
      context
    }));
  }

  /**
   * 获取上下文统计信息
   */
  getContextStats(): {
    totalContexts: number;
    totalMessages: number;
    averageMessagesPerContext: number;
    oldestContextAge: number;
    newestContextAge: number;
  } {
    const contexts = Array.from(this.contexts.values());
    const totalContexts = contexts.length;
    const totalMessages = contexts.reduce((sum, ctx) => sum + ctx.history.length, 0);
    const averageMessagesPerContext = totalContexts > 0 ? totalMessages / totalContexts : 0;

    let oldestTimestamp = Date.now();
    let newestTimestamp = 0;

    contexts.forEach(context => {
      if (context.history.length > 0) {
        const firstMessage = context.history[0];
        const lastMessage = context.history[context.history.length - 1];
        
        if (firstMessage.timestamp < oldestTimestamp) {
          oldestTimestamp = firstMessage.timestamp;
        }
        if (lastMessage.timestamp > newestTimestamp) {
          newestTimestamp = lastMessage.timestamp;
        }
      }
    });

    const now = Date.now();
    const oldestContextAge = totalContexts > 0 ? now - oldestTimestamp : 0;
    const newestContextAge = totalContexts > 0 ? now - newestTimestamp : 0;

    return {
      totalContexts,
      totalMessages,
      averageMessagesPerContext: Math.round(averageMessagesPerContext * 100) / 100,
      oldestContextAge,
      newestContextAge
    };
  }

  /**
   * 执行定期清理
   */
  private performPeriodicCleanup(): void {
    const now = Date.now();
    
    if (now - this.lastCleanup > this.cleanupInterval) {
      this.cleanupInactiveContexts();
      this.lastCleanup = now;
    }
  }

  /**
   * 清理不活跃的对话上下文
   */
  private cleanupInactiveContexts(): void {
    const now = Date.now();
    const keysToRemove: string[] = [];

    for (const [key, context] of this.contexts.entries()) {
      // 检查上下文是否长时间未活跃
      const lastActivity = this.getLastActivityTime(context);
      
      if (now - lastActivity > this.contextTimeout) {
        keysToRemove.push(key);
      }
    }

    // 移除不活跃的上下文
    keysToRemove.forEach(key => {
      this.contexts.delete(key);
      console.log(`🗑️ 清理不活跃的对话上下文: ${key}`);
    });

    if (keysToRemove.length > 0) {
      console.log(`🧹 清理完成，移除了 ${keysToRemove.length} 个不活跃的对话上下文`);
    }
  }

  /**
   * 获取上下文的最后活跃时间
   */
  private getLastActivityTime(context: ConversationContext): number {
    if (context.history.length === 0) {
      return Date.now(); // 新创建的上下文
    }
    
    const lastMessage = context.history[context.history.length - 1];
    return lastMessage.timestamp;
  }

  /**
   * 设置最大历史记录长度
   */
  setMaxHistoryLength(length: number): void {
    this.maxHistoryLength = Math.max(1, length);
    
    // 对现有上下文应用新的限制
    for (const context of this.contexts.values()) {
      if (context.history.length > this.maxHistoryLength) {
        context.history = context.history.slice(-this.maxHistoryLength);
      }
    }
  }

  /**
   * 设置上下文超时时间
   */
  setContextTimeout(timeout: number): void {
    this.contextTimeout = Math.max(60000, timeout); // 最少1分钟
  }

  /**
   * 强制清理所有上下文
   */
  clearAllContexts(): void {
    const count = this.contexts.size;
    this.contexts.clear();
    console.log(`🗑️ 清除了所有 ${count} 个对话上下文`);
  }

  /**
   * 导出上下文数据（用于调试或备份）
   */
  exportContexts(): any {
    const data: any = {};
    
    for (const [key, context] of this.contexts.entries()) {
      data[key] = {
        entityId: context.entityId,
        entityType: context.entityType,
        historyCount: context.history.length,
        lastActivity: this.getLastActivityTime(context),
        gameContext: context.gameContext
      };
    }
    
    return {
      timestamp: Date.now(),
      contexts: data,
      stats: this.getContextStats()
    };
  }

  /**
   * 获取特定实体类型的所有上下文
   */
  getContextsByEntityType(entityType: string): ConversationContext[] {
    const contexts: ConversationContext[] = [];
    
    for (const [key, context] of this.contexts.entries()) {
      if (context.entityType === entityType) {
        contexts.push(context);
      }
    }
    
    return contexts;
  }

  /**
   * 检查实体是否有活跃的对话上下文
   */
  hasActiveContext(entityId: string, entityType: string): boolean {
    const contextKey = `${entityType}_${entityId}`;
    return this.contexts.has(contextKey);
  }

  /**
   * 获取上下文的详细信息（用于调试）
   */
  getContextDetails(entityId: string, entityType: string): any {
    const contextKey = `${entityType}_${entityId}`;
    const context = this.contexts.get(contextKey);
    
    if (!context) {
      return null;
    }
    
    return {
      key: contextKey,
      entityId: context.entityId,
      entityType: context.entityType,
      historyLength: context.history.length,
      lastActivity: this.getLastActivityTime(context),
      gameContext: context.gameContext,
      recentMessages: context.history.slice(-5).map(msg => ({
        sender: msg.sender,
        content: msg.content.substring(0, 50) + (msg.content.length > 50 ? '...' : ''),
        timestamp: new Date(msg.timestamp).toLocaleTimeString()
      }))
    };
  }

  /**
   * 清理资源
   */
  dispose(): void {
    this.clearAllContexts();
  }
}

// 导出单例实例
export const conversationContextManager = new ConversationContextManager();